package top.eggcode.plugins.dict;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.FieldUtils;
import top.eggcode.common.error.ServiceLogicException;
import top.eggcode.common.lang.BeanUnit;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;

/**
 * Title:
 * Description: TODO
 * Date: 2021/5/22 23:59
 *
 * @author JiaQi Ding
 * @version 1.0
 */
public final class Translator {

    private static DictSource dataSource;

    public static void setDataSource(DictSource dataSource) {
        Translator.dataSource = dataSource;
    }

    public static <T> void start(T source) {
        FieldUtils.getAllFieldsList(source.getClass()).forEach(field -> {
            // 注解标记
            boolean annotationFlag = field.isAnnotationPresent(Word.class);
            // 假设存在@Word注解
            if (annotationFlag) {
                Word anno = field.getAnnotation(Word.class);
                String dictCode = anno.dict();

                try {
                    String sourceField = anno.source();
                    Object value = null;
                    if (StringUtils.isNotBlank(sourceField)) {
                        value = BeanUnit.getAttributeValue(sourceField, source);
                    } else {
                        value = BeanUnit.getAttributeValue(field.getName(), source);
                    }
                    // 等于 null 跳过
                    if (value != null) {
                        if (!(value instanceof String || value instanceof Integer || value instanceof Short || value instanceof Long)) {
                            throw new ServiceLogicException("Object Type: " + source.getClass().getName() + ", Field: " + sourceField + " 不是字符串或整数类型，翻译中断");
                        }
                        // 获取方言
                        String vernacular = dataSource.getWord(dictCode, String.valueOf(value));
                        // 设置属性
                        BeanUnit.setAttributeValue(field.getName(), vernacular, source);
                    }

                } catch (InvocationTargetException | IllegalAccessException | IntrospectionException e) {
                    e.printStackTrace();
                }
            }

        });
    }
}
